package com.sgb.kjwl.viewmodel.manage;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.alibaba.sdk.android.vod.upload.VODUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.model.UploadFileInfo;
import com.alibaba.sdk.android.vod.upload.model.VodInfo;
import com.blankj.utilcode.util.RegexUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.UrlConfig;
import com.sgb.kjwl.api.service.WebsiteInfoAPI;
import com.swgk.core.view.entity.AliProofEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.activity.manage.UploadPicAndVideoActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author 张驰
 * @date 2021/5/10 15:37
 * @Description 企业网站发布列表
 * @name com.sgb.kjwl.viewmodel.manage
 */
public class UploadPicViedeoModel extends BaseViewModel {

    private UploadPicAndVideoActivity activity;
    private final VODUploadClientImpl mUploadClient;

    public UploadPicViedeoModel(UploadPicAndVideoActivity activity) {
        this.activity = activity;
        mUploadClient = new VODUploadClientImpl(activity.getApplicationContext());
    }

    private AliProofEntity mProofEntity;

    private MutableLiveData<String> pic_video_paths = new MutableLiveData<>();

    public MutableLiveData<String> getPic_video_paths() {
        return pic_video_paths;
    }

    public MutableLiveData<List<PickSelectEntity>> upLoadTypes = new MutableLiveData();

    public void setPic_video_paths(MutableLiveData<String> pic_video_paths) {
        this.pic_video_paths = pic_video_paths;
    }

    /**
     * 编辑或新增
     */
    public void saveOrUpdate( Map<String, Object> map) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getWebsiteInfoAPI().addOrUpdateCompanyAlbum(WebsiteInfoAPI.WebsiteUrl.URL_ADD_UPDATE_COMPANY_ALBUM, map).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    getMessage().postValue("操作成功");
                }
            }
        });
       APIManager.getInstance().changeAPIManager(UrlConfig.BASE_URL);
    }


    public void uploadAvatar( File file) {
        DialogHelper.showProgressDialog(activity, null, "图片上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        //创建map集合
        Map<String, RequestBody> photos = new HashMap<>();
        //将文件转换成多媒体文件，方便上传
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + RegexUtils.getReplaceAll(file.getName(), "[\u4e00-\u9fa5]", "") +  "image.jpg\"", requestBody);
        //接口请求
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data == null || data.getData() == null) {
                    MToast.showToast(activity, "上传失败");
                    return;
                }
                pic_video_paths.postValue(data.getData().toString());
            }
        });
    }


    // -----获取视频---------------------------------------------------------------------------

    public void videoSelector(int number, int requestCode) {
        PictureSelector.create(activity)
                .openGallery(PictureMimeType.ofVideo())
                .imageEngine(GlideEngine.createGlideEngine())
                .selectionMode(PictureConfig.MULTIPLE)
                .isCompress(true)//是否压缩
                .minimumCompressSize(10240)//小于10M不压缩
                .maxSelectNum(number)//判断还能选多少张图片
                .forResult(requestCode);
    }

    //获取视频上传凭证
    public void getVideoParamsSTS(String path) {
        DialogHelper.showProgressDialog(activity, null, "视频处理中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        APIManager.getInstance().getWebsiteInfoAPI().getVideoParams(map).enqueue(new Callback<BaseEntity<AliProofEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<AliProofEntity>> call, Response<BaseEntity<AliProofEntity>> response) {
                    if (response.body().getState().equals("ok")) {
                        mProofEntity = response.body().getData();
                        VodInfo vodInfo = new VodInfo();
                        vodInfo.setTitle("");
                        vodInfo.setDesc("");
                        vodInfo.setCateId((int) System.currentTimeMillis());
                        vodInfo.setTags(null);
                        mUploadClient.addFile(path, vodInfo);
                        //阿里凭证
                        mUploadClient.init(mUploadCallback);
                        mUploadClient.start();
                    } else {
                        DialogHelper.dismissProgressDialog();
                        MToast.showToast(activity, "上传失败");
                    }
            }

            @Override
            public void onFailure(Call<BaseEntity<AliProofEntity>> call, Throwable t) {
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    VODUploadCallback mUploadCallback = new VODUploadCallback() {
        public void onUploadSucceed(UploadFileInfo info) {
            Log.e("onUploadSucceed", "onUploadSucceed");
            activity.uploadVideoResult(mProofEntity.getVideoId(), info);
        }

        public void onUploadFailed(UploadFileInfo info, String code, String message) {
            Log.e("onUploadFailed", "onUploadFailed code = " + code + "  message == " + message);
        }

        public void onUploadProgress(UploadFileInfo info, long uploadedSize, long totalSize) {
            Log.e("onUploadFailed", "onUploadFailed");
        }

        public void onUploadTokenExpired() {
            Log.e("onUploadTokenExpired", "onUploadTokenExpired");
            mUploadClient.resumeWithAuth(mProofEntity.getUploadAuth());
        }

        public void onUploadRetry(String code, String message) {
            Log.e("onUploadRetry", "onUploadRetry");
        }

        public void onUploadRetryResume() {
            Log.e("onUploadRetryResume", "onUploadRetryResume");
        }

        public void onUploadStarted(UploadFileInfo uploadFileInfo) {
            Log.e("onUploadStarted", "onUploadStarted");
            mUploadClient.setUploadAuthAndAddress(uploadFileInfo, mProofEntity.getUploadAuth(), mProofEntity.getUploadAddress());
        }
    };


    /************************************************************************************
     * 上传类型
     * */
    public void getUploadType() {
        List<PickSelectEntity> list = new ArrayList<>();
        PickSelectEntity pickSelectEntity1 = new PickSelectEntity();
        PickSelectEntity pickSelectEntity2 = new PickSelectEntity();
        pickSelectEntity1.setProjectscale("图片/视频");
        pickSelectEntity1.setNo("");
        pickSelectEntity2.setProjectscale("VR实景");
        pickSelectEntity2.setNo("3");
        list.add(pickSelectEntity1);
        list.add(pickSelectEntity2);
        upLoadTypes.postValue(list);
    }

}
